package com.starry.module.system.core.file.controller.admin;

import cn.hutool.core.util.URLUtil;
import com.starry.core.common.domain.R;
import com.starry.core.web.core.controller.BaseController;
import com.starry.module.system.api.file.domain.qo.SysFileQo;
import com.starry.module.system.core.file.entity.SysFile;
import com.starry.module.system.core.file.service.FileService;
import com.starry.module.system.core.file.service.SysFileService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import static com.starry.module.system.core.file.client.utils.FileTypeUtils.writeAttachment;

/**
 * 文件存储
 *
 * @author xiaoke
 */
@Tag(name = "文件存储")
@RestController
@RequestMapping("system/file")
public class FileController extends BaseController {

    private final FileService fileService;
    private final SysFileService sysFileService;

    public FileController(FileService fileService, SysFileService sysFileService) {
        this.fileService = fileService;
        this.sysFileService = sysFileService;
    }

    /**
     * 上传文件
     * @param file 文件
     */
    @PostMapping("/upload/public")
    @Operation(summary = "上传文件（公开）")
    public R<SysFileQo> uploadPublicFile(@RequestParam("file") MultipartFile file) throws Exception {
        return success(fileService.createFile(file, true));
    }

    /**
     * 上传文件
     * @param file 文件
     */
    @PostMapping("/upload")
    @Operation(summary = "上传文件")
    public R<SysFileQo> uploadFile(@RequestParam("file") MultipartFile file) throws Exception {
        return success(fileService.createFile(file, true));
    }

    @Operation(summary = "下载文件（公开）")
    @GetMapping("/public/download/{configId}/{fileName}")
    public void downloadPublic(
            HttpServletResponse response,
            @PathVariable("configId") Long configId,
            @PathVariable("fileName") String fileName
    ) throws Exception {
        fileName = URLUtil.decode(fileName);
        SysFile sysFile = sysFileService.get(configId, fileName);
        byte[] content = fileService.getFileContent(configId, sysFile.getFilePath());
        writeAttachment(response, fileName, content);
    }

    @Operation(summary = "下载文件")
    @GetMapping("/public/{configId}/{fileName}")
    public void download(
            HttpServletResponse response,
            @PathVariable("configId") Long configId,
            @PathVariable("fileName") String fileName
    ) throws Exception {
        fileName = URLUtil.decode(fileName);
        SysFile sysFile = sysFileService.get(configId, fileName);
        byte[] content = fileService.getFileContent(configId, sysFile.getFilePath());
        writeAttachment(response, fileName, content);
    }
}
